import os
import subprocess
import sys
import logging

# 隐藏sentence-transformers的日志消息
logging.getLogger('sentence_transformers').setLevel(logging.ERROR)

def check_mysql():
    """检查MySQL是否已启动"""
    print("正在检查MySQL服务...")
    try:
        import pymysql
        conn = pymysql.connect(
            host=os.getenv('MYSQL_HOST', 'localhost'),
            port=int(os.getenv('MYSQL_PORT', 3307)),
            user=os.getenv('MYSQL_USER', 'root'),
            password=os.getenv('MYSQL_PASSWORD', '123456'),
            charset='utf8mb4'
        )
        conn.close()
        return True
    except Exception as e:
        print(f"MySQL连接失败: {e}")
        print("请确保MySQL服务已在端口3307上启动，用户名为root，密码为123456")
        return False

def main():
    """主函数，运行后端服务"""
    # 检查环境变量文件是否存在
    if not os.path.exists('.env'):
        if os.path.exists('config.env'):
            print("找到config.env文件，正在复制为.env文件...")
            with open('config.env', 'r', encoding='utf-8') as src:
                with open('.env', 'w', encoding='utf-8') as dst:
                    dst.write(src.read())
        else:
            print("错误：找不到.env或config.env文件。请确保配置文件存在。")
            sys.exit(1)

    # 检查MySQL是否已启动
    if not check_mysql():
        sys.exit(1)

    # 尝试初始化数据库
    print("正在初始化数据库...")
    try:
        from setup_db import setup_database
        setup_database()
    except Exception as e:
        print(f"初始化数据库失败: {e}")
        answer = input("是否继续启动应用? (y/n): ")
        if answer.lower() != 'y':
            sys.exit(1)

    # 启动后端服务
    print("正在启动后端服务...")
    try:
        from app import app
        app.run(host='0.0.0.0', port=5000, debug=True)
    except Exception as e:
        print(f"启动服务失败: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main() 